package cn.ac.jaas.isc.vegetable.common.log.aspect;

import cn.ac.jaas.isc.vegetable.admin.api.dto.SysLogDTO;
import cn.ac.jaas.isc.vegetable.common.log.annotation.SysLog;
import cn.ac.jaas.isc.vegetable.common.log.event.SysLogEvent;
import cn.ac.jaas.isc.vegetable.common.log.util.LogTypeEnum;
import cn.ac.jaas.isc.vegetable.common.log.util.SysLogUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.ApplicationEventPublisher;

/**
 * @author 张高昌
 * @date 2022/4/2 19:51
 * @description: @Aspect @Around ProceedingJoinPoint都是从common-excel中获取到的jar
 */
@Slf4j
@Aspect
@RequiredArgsConstructor
public class SysLogAspect {

    private final ApplicationEventPublisher publisher;

    @SneakyThrows
    @Around("@annotation(sysLog)")
    public Object around(ProceedingJoinPoint point, SysLog sysLog) {
        String strClassName = point.getTarget().getClass().getName();
        String strMethodName = point.getSignature().getName();
        log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);

        SysLogDTO logDTO = SysLogUtils.getSysLog();
        logDTO.setTitle(sysLog.value());
        // 发送异步日志事件
        Long startTime = System.currentTimeMillis();
        Object obj;
        try {
            obj = point.proceed();
        }
        catch (Exception e) {
            logDTO.setType(LogTypeEnum.ERROR.getType());
            logDTO.setException(e.getMessage());
            throw e;
        }
        finally {
            Long endTime = System.currentTimeMillis();
            logDTO.setTime(endTime - startTime);
            publisher.publishEvent(new SysLogEvent(logDTO));
        }
        return obj;
    }
}
